package com.photoeditor.demo.model.subscribe.strategy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.SparseArray;

//import com.common.commercialize.strategy.StrategyManager;
import com.common.commercialize.channel.BuyUserManager;
import com.common.commercialize.strategy.StrategyManager;
import com.photoeditor.R;
//import com.photoeditor.demo.ad.CameraStrategyConstant;
import com.photoeditor.demo.ad.CameraStrategyConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.bean.sub.SubBannerBean;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant.SVipEntrance;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.util.TimeConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_ADVANCE_FEATURE;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_EDIT;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_FUNCTION_SUBSCRIBE;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_PICTUREME_FORTUNE_YEAR;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_IN_APP;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_RETAIN;
import static com.photoeditor.demo.model.subscribe.strategy.SVipStrategyBean.StrategyBeanConfig;

/**
 * 付费订阅入口策略管理类
 * Created by Lai on 2018/10/25 0025.
 */
public class SVipStrategyManager {

    //all
    public static final int FUNCTION_PALM = 0;
    public static final int FUNCTION_FACE_AGING = 1;
    public static final int FUNCTION_EXOTIC = 2;
    public static final int FUNCTION_PREVIOUS_LIFE = 3;
    public static final int FUNCTION_GENDER_SWITCH = 4;
    public static final int FUNCTION_BABY = 5;
    public static final int FUNCTION_BALL = 6;
    public static final int FUNCTION_LUCKY = 7;
    public static final int FUNCTION_HOROSCOPE = 8;
    public static final int FUNCTION_ETHNICITY = 9;
    public static final int FUNCTION_LOVE_MATCH = 10;
    public static final int FUNCTION_HOROSCOPE_MATCH = 11;
    public static final int FUNCTION_FACE_AGING_SCANNER = 12;
    private static final int ENTRANCE_RETAIN = 13;

    //hot
    public static final int FUNCTION_PALM_HOT = 20;
    public static final int FUNCTION_FACE_AGING_HOT = 21;
    public static final int FUNCTION_BABY_HOT = 22;
    public static final int FUNCTION_BALL_HOT = 23;
    public static final int FUNCTION_LUCKY_HOT = 24;
    public static final int FUNCTION_HOROSCOPE_HOT = 25;
    public static final int FUNCTION_ETHNICITY_HOT = 26;
    public static final int FUNCTION_LOVE_MATCH_HOT = 27;
    public static final int FUNCTION_HOROSCOPE_MATCH_HOT = 28;
    public static final int FUNCTION_EXOTIC_HOT = 29;
    public static final int FUNCTION_PREVIOUS_LIFE_HOT = 30;
    public static final int FUNCTION_GENDER_SWITCH_HOT = 31;
    public static final int FUNCTION_FACE_AGING_SCANNER_HOT = 32;

    //new
    public static final int FUNCTION_PALM_NEW = 40;
    public static final int FUNCTION_FACE_AGING_NEW = 41;
    public static final int FUNCTION_BABY_NEW = 42;
    public static final int FUNCTION_BALL_NEW = 43;
    public static final int FUNCTION_LUCKY_NEW = 44;
    public static final int FUNCTION_HOROSCOPE_NEW = 45;
    public static final int FUNCTION_ETHNICITY_NEW = 46;
    public static final int FUNCTION_LOVE_MATCH_NEW = 47;
    public static final int FUNCTION_HOROSCOPE_MATCH_NEW = 48;
    public static final int FUNCTION_EXOTIC_NEW = 49;
    public static final int FUNCTION_PREVIOUS_LIFE_NEW = 50;
    public static final int FUNCTION_GENDER_SWITCH_NEW = 51;
    public static final int FUNCTION_FACE_AGING_SCANNER_NEW = 52;

    private List<StrategyBeanConfig> mConfigs;
    private SparseArray<StrategyBeanConfig> mConfigMap;
    private int mFunId;
    private List<SubBannerBean.BannerBean> mDefaultBanners;

    private static class Holder {
        private static SVipStrategyManager sInstance = new SVipStrategyManager();
    }

    public static SVipStrategyManager getInstance() {
        return Holder.sInstance;
    }

    private SVipStrategyManager() {
    }

    public void init() {
        checkEmpty();
        mFunId = CameraStrategyConstant.FUN_ID_SVIP;
        StrategyManager.getInstance().registerStrategy(mFunId,
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        updateStrategy();
                    }
                });
        updateStrategy();
    }


    private void updateStrategy() {
        //得到真正下发的config集合
        mConfigs = StrategyManager.getInstance().getStrategyConfig(mFunId, SVipStrategyBean.class);
        if (mConfigs != null && !mConfigs.isEmpty()) {
            checkEmpty();
            for (StrategyBeanConfig config : mConfigs) {
                //根据订阅类型（主订阅页，挽留弹窗，功能订阅页）
                switch (config.getEntranceId()) {
                    //主订阅页
                    case VIP_ENTRANCE_IN_APP:
                        mConfigMap.get(VIP_ENTRANCE_IN_APP).update(config);
                        break;
                    //挽留弹窗
                    case VIP_ENTRANCE_RETAIN:
                        mConfigMap.get(VIP_ENTRANCE_RETAIN).update(config);
                        break;
                    //功能订阅页
                    case VIP_ENTRANCE_FUNCTION_SUBSCRIBE:
                        mConfigMap.get(VIP_ENTRANCE_FUNCTION_SUBSCRIBE).update(config);
                        break;
                    case VIP_ENTRANCE_ADVANCE_FEATURE:
                        mConfigMap.get(VIP_ENTRANCE_ADVANCE_FEATURE).update(config);
                        break;
                }
            }
        }
    }

    private void checkEmpty() {
        //从后端获取到了策略则直接退出
        if (mConfigMap != null) {
            return;
        }
        //默认配置
        mConfigMap = new SparseArray<>();
        StrategyBeanConfig config = new StrategyBeanConfig(true, VIP_ENTRANCE_IN_APP,SVipConstant.VIP_ACTIVITY_A, SVipConstant.COLOR_DARK,SVipConstant.COLOR_DARK,true);
        mConfigMap.put(VIP_ENTRANCE_IN_APP, config);

        config = new StrategyBeanConfig(VIP_ENTRANCE_RETAIN, true, SVipConstant.VIP_RETAIN_A,SVipConstant.COLOR_DARK,SVipConstant.COLOR_DARK, 2, true);
        mConfigMap.put(VIP_ENTRANCE_RETAIN, config);

        config = new StrategyBeanConfig(true,VIP_ENTRANCE_FUNCTION_SUBSCRIBE,  SVipConstant.COLOR_DARK,SVipConstant.COLOR_DARK, true);
        mConfigMap.put(VIP_ENTRANCE_FUNCTION_SUBSCRIBE, config);

        config = new StrategyBeanConfig(VIP_ENTRANCE_ADVANCE_FEATURE, SVipConstant.VIP_FUTURE_A, true);
        mConfigMap.put(VIP_ENTRANCE_ADVANCE_FEATURE, config);

        config = new StrategyBeanConfig(VIP_ENTRANCE_EDIT, SVipConstant.VIP_ACTIVITY_A, true);
        mConfigMap.put(VIP_ENTRANCE_EDIT, config);
    }

    /**
     * 目前只有一种样式，写死类型（主订阅页）
     *
     * @param entrance
     * @return
     */
    public int getWitchPage(@SVipConstant.SVipEntrance int entrance) {
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(entrance);
        if (config == null) {
            config = mConfigMap.get(VIP_ENTRANCE_IN_APP);
        }
        if (config != null && config.getTestPageId() > 0) {
            return config.getTestPageId();
        }

        return config.getDefaultPageId();
    }

    /**
     * 返回AB样式（挽留弹窗）
     * @param entrance
     * @return
     */
    public int getWitchPageWithAB(@SVipConstant.SVipEntrance int entrance) {
        checkEmpty();
        if (SVipConstant.isFortuneEntrance(entrance)) {
            //年月周运势使用同一个策略
            entrance = VIP_ENTRANCE_PICTUREME_FORTUNE_YEAR;
        }
        StrategyBeanConfig config = mConfigMap.get(entrance);
        if (config == null) {
            config = mConfigMap.get(SVipConstant.VIP_ENTRANCE_IN_APP);
        }
        if (config != null && config.getTestPageId() > 0) {
            return config.getTestPageId();
        }
        if (SVipConstant.isABActivity(entrance)) {
            return SVipConstant.VIP_ACTIVITY_A;
        } else if (SVipConstant.isABDialog(entrance)) {
            return SVipConstant.VIP_DIALOG_B;
        }
        return config.getDefaultPageId();
    }

    //根据entrance(主订阅页，挽留弹窗，功能订阅页)获取付费文案的颜色（深1，浅0）
    public int getWitchColorPay(@SVipConstant.SVipEntrance int entrance) {
        //先update策略，获取到了则不设置默认的配置，checkEmpty return,拿真正的配置
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(entrance);
        //没有获取到配置则使用默认的功能订阅页的深色颜色
        if (config == null) {
            config = mConfigMap.get(SVipConstant.VIP_ENTRANCE_FUNCTION_SUBSCRIBE);
        }
        //拿到了则使用真正的配置
        if (config != null && config.getPayColor() >= 0) {
            return config.getPayColor();
        }
        //默认客户端深色
        return config.getDefaultPayColor();
    }

    //根据entrance(主订阅页，挽留弹窗，功能订阅页)获取套餐介绍文案的颜色（深1，浅0）
    public int getWitchColorDes(@SVipConstant.SVipEntrance int entrance) {
        //先update策略，获取到了则不设置默认的配置，checkEmpty return,拿真正的配置
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(entrance);
        //没有获取到配置则使用默认的
        if (config == null) {
            config = mConfigMap.get(SVipConstant.VIP_ENTRANCE_FUNCTION_SUBSCRIBE);
        }
        //拿到了则使用真正的配置
        if (config != null && config.getDesColor() >= 0) {
            return config.getDesColor();
        }
        //默认客户端深色
        return config.getDefaultDesColor();
    }

    public int getFirstSubscribeType() {
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(VIP_ENTRANCE_IN_APP);
        if (config != null && config.getFirstSub() > 0) {
            return config.getFirstSub();
        }
        return SkuManager.TYPE_YEARLY;
    }

    public boolean canShowSVip(@SVipConstant.SVipEntrance int entrance) {
        if (AppVipManager.isVip()) {
            return false;
        }
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(entrance);
        if (config == null) {
            return true;
        }
        if (!config.isOpen()) {
            return false;
        }
        if (config.getShowCountToday() > 0) {
            long lastShowTime = getLastShowTime(entrance);
            if (isToday(lastShowTime)) {
                if ((getShowCountToday(entrance)) >= config.getShowCountToday()) {
                    return false;
                }
            } else {
                setShowCountToday(entrance, 0);
            }
        }

        return true;
    }

    public boolean canShowRetain() {
        if (AppVipManager.isVip()) {
            return false;
        }
        checkEmpty();
        StrategyBeanConfig config = mConfigMap.get(VIP_ENTRANCE_RETAIN);
        if (config == null) {
            return true;
        }
        if (!config.isOpen()) {
            return false;
        }
        long lastShowTime = getLastShowTime(VIP_ENTRANCE_RETAIN);
        int count=getShowCountToday(VIP_ENTRANCE_RETAIN);
        if (isToday(lastShowTime)) {
            if (count >= config.getShowCountToday()) {
                return false;
            }
        }else {
            setShowCountToday(VIP_ENTRANCE_RETAIN, 0);
            count = 0;
        }

        saveLastShowTime(VIP_ENTRANCE_RETAIN);
        setShowCountToday(VIP_ENTRANCE_RETAIN, ++count);
        return true;

    }

    public boolean canShowBottomTipText(@SVipConstant.SVipEntrance int entrance) {
        return true;
//        if (AppVipManager.isVip()) {
//            return false;
//        }
//        if (!BuyUserManager.getInstance().isBuyUser() && !TestUser.isTestUser()) {
//            return true;
//        }
//        checkEmpty();
//        StrategyBeanConfig config = mConfigMap.get(entrance);
//        if (config == null) {
//            return false;
//        }
//        return config.getShowTipText();
    }

    public List<SubBannerBean.BannerBean> getBanners() {
        checkEmpty();
//        StrategyBeanConfig config = mConfigMap.get(VIP_ENTRANCE_IN_APP);
//        if (config == null) {
//            return getDefaultBanners();
//        }
//        String json = config.getBannerJson();
//        if (!TextUtils.isEmpty(json)) {
//            try {
//                SubBannerBean subBannerBean = new Gson().fromJson(json, SubBannerBean.class);
//                if (subBannerBean != null) {
//                    List<SubBannerBean.BannerBean> banners = subBannerBean.getBanners();
//                    String rootUrl = subBannerBean.getRootUrl();
//                    int[] array = ComponentContext.getContext().getResources().getIntArray(R.array.banner_titles);
//                    if (!TextUtils.isEmpty(rootUrl) && banners != null && !banners.isEmpty()) {
//                        for (SubBannerBean.BannerBean bannerBean : banners) {
//                            bannerBean.setBanner(rootUrl + bannerBean.getBanner());
//                            bannerBean.setTextResId(array[Integer.valueOf(bannerBean.getTab())]);
//                        }
//                        return banners;
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return getDefaultBanners();
    }

    private List<SubBannerBean.BannerBean> getDefaultBanners() {
        if (mDefaultBanners == null) {
            mDefaultBanners = new ArrayList<>();
            SubBannerBean.BannerBean bannerBean;
            bannerBean = new SubBannerBean.BannerBean(R.drawable.ic_subscribe_function_artistic_filter, R.string.vip_banner_artistic_filter);
            mDefaultBanners.add(bannerBean);
            bannerBean = new SubBannerBean.BannerBean(R.drawable.ic_subscribe_function_time_machine, R.string.vip_banner_time_machine_magic);
            mDefaultBanners.add(bannerBean);
            bannerBean = new SubBannerBean.BannerBean(R.drawable.ic_subscribe_function_filters, R.string.vip_banner_more_filters);
            mDefaultBanners.add(bannerBean);
            bannerBean = new SubBannerBean.BannerBean(R.drawable.ic_subscribe_function_fashion_sticker, R.string.vip_banner_fashion_sticker);
            mDefaultBanners.add(bannerBean);
        }
        return mDefaultBanners;
    }

    public boolean getCanShowFunction(int funId) {
        StrategyBeanConfig config = mConfigMap.get(VIP_ENTRANCE_IN_APP);
        boolean canShow = false;
        switch (funId) {
            case FUNCTION_PALM:
//                canShow = config.isPalmShow();
                break;
            case FUNCTION_FACE_AGING:
//                canShow = config.isAgingShow();
                break;
            case FUNCTION_EXOTIC:
//                canShow = config.isExoticShow();
                break;
            case FUNCTION_PREVIOUS_LIFE:
//                canShow = config.isPreviousLifeShow();
                break;
            case FUNCTION_GENDER_SWITCH:
//                canShow = config.isGenderSwitchShow();
                break;
            case FUNCTION_BABY:
//                canShow = config.isBabyShow();
                canShow = false;
                break;
            case FUNCTION_BALL:
//                canShow = config.isBallShow();
                break;
            case FUNCTION_LUCKY:
//                canShow = config.isLuckyShow();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE:
//                canShow = config.isHoroscopeShow();
                canShow = false;
                break;
            case FUNCTION_ETHNICITY:
//                canShow = config.isEthnicityShow();
                canShow = false;
                break;
            case FUNCTION_LOVE_MATCH:
//                canShow = config.isLoveMatchShow();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE_MATCH:
//                canShow = config.isHoroscopeMatchShow();
                canShow = false;
                break;
            case FUNCTION_FACE_AGING_SCANNER:
//                canShow = config.isAgingScannerShow();
                canShow = true;
                break;
            case FUNCTION_PALM_HOT:
//                canShow = config.isPalmShowHot();
                break;
            case FUNCTION_FACE_AGING_HOT:
//                canShow = config.isAgingShowHot();
                break;
            case FUNCTION_BABY_HOT:
//                canShow = config.isBabyShowHot();
                canShow = false;
                break;
            case FUNCTION_BALL_HOT:
//                canShow = config.isBallShowHot();
                break;
            case FUNCTION_LUCKY_HOT:
//                canShow = config.isLuckyShowHot();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE_HOT:
//                canShow = config.isHoroscopeShowHot();
                canShow = false;
                break;
            case FUNCTION_ETHNICITY_HOT:
//                canShow = config.isEthnicityShowHot();
                canShow = false;
                break;
            case FUNCTION_LOVE_MATCH_HOT:
//                canShow = config.isLoveMatchShowHot();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE_MATCH_HOT:
//                canShow = config.isHoroscopeMatchShowHot();
                canShow = false;
                break;
            case FUNCTION_EXOTIC_HOT:
//                canShow = config.isExoticShowHot();
                break;
            case FUNCTION_PREVIOUS_LIFE_HOT:
//                canShow = config.isPreviousLifeShowHot();
                break;
            case FUNCTION_GENDER_SWITCH_HOT:
//                canShow = config.isGenderSwitchShowHot();
                break;
            case FUNCTION_FACE_AGING_SCANNER_HOT:
//                canShow = config.isAgingScannerShowHot();
                canShow = false;
                break;
            case FUNCTION_PALM_NEW:
//                canShow = config.isPalmShowNew();
                break;
            case FUNCTION_FACE_AGING_NEW:
//                canShow = config.isAgingShowNew();
                break;
            case FUNCTION_BABY_NEW:
//                canShow = config.isBabyShowNew();
                canShow = false;
                break;
            case FUNCTION_BALL_NEW:
//                canShow = config.isBallShowNew();
                break;
            case FUNCTION_LUCKY_NEW:
//                canShow = config.isLuckyShowNew();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE_NEW:
//                canShow = config.isHoroscopeShowNew();
                canShow = false;
                break;
            case FUNCTION_ETHNICITY_NEW:
//                canShow = config.isEthnicityShowNew();
                canShow = false;
                break;
            case FUNCTION_LOVE_MATCH_NEW:
//                canShow = config.isLoveMatchShowNew();
                canShow = false;
                break;
            case FUNCTION_HOROSCOPE_MATCH_NEW:
//                canShow = config.isHoroscopeMatchShowNew();
                canShow = false;
                break;
            case FUNCTION_EXOTIC_NEW:
//                canShow = config.isExoticShowNew();
                break;
            case FUNCTION_PREVIOUS_LIFE_NEW:
//                canShow = config.isPreviousLifeShowNew();
                break;
            case FUNCTION_GENDER_SWITCH_NEW:
//                canShow = config.isGenderSwitchShowNew();
                break;
            case FUNCTION_FACE_AGING_SCANNER_NEW:
//                canShow = config.isAgingScannerShowNew();
                canShow = false;
                break;
            default:
                break;
        }
        return canShow;
    }

    public void saveLastShowTime(@SVipEntrance int entrance) {
        SpUtils.obtain().save(SVipConstant.getSPNameByEntrance(entrance) + "_lst", System.currentTimeMillis());
    }

    private long getLastShowTime(@SVipEntrance int entrance) {
        return SpUtils.obtain().getLong(SVipConstant.getSPNameByEntrance(entrance) + "_lst", 0);
    }

    private void setShowCountToday(@SVipEntrance int entrance, int count) {
        SpUtils.obtain().save(SVipConstant.getSPNameByEntrance(entrance) + "_scto", count);
    }

    public void saveShowCountToday(@SVipEntrance int entrance) {
        int showCountToday = getShowCountToday(entrance);
        SpUtils.obtain().save(SVipConstant.getSPNameByEntrance(entrance) + "_scto", ++showCountToday);
    }

    private int getShowCountToday(@SVipEntrance int entrance) {
        return SpUtils.obtain().getInt(SVipConstant.getSPNameByEntrance(entrance) + "_scto", 0);
    }

    public static boolean hasShowMainAfterSub() {
        return SpUtils.obtain().getBoolean("h_s_m_a_s", false);
    }

    public static void setHasShowMainAfterSub() {
        SpUtils.obtain().save("h_s_m_a_s", true);
    }

    public static boolean hasLeaveFromSub() {
        return SpUtils.obtain().getBoolean("h_l_f_s", false);
    }

    public static void setHasLeaveFromSub() {
        SpUtils.obtain().save("h_l_f_s", true);
    }

    public static boolean hasStatisticReopen() {
        return SpUtils.obtain().getBoolean("h_s_re_o", false);
    }

    public static void setHasStatisticReopen() {
        SpUtils.obtain().save("h_s_re_o", true);
    }

    /**
     * @param funAlias @SVipConstant#getAliasByFunType(int)
     */
    public static void addUsedFeature(String funAlias) {
        String string = getUsedFeature();
        if (TextUtils.isEmpty(string) || TextUtils.isEmpty(string.replace("_", ""))) {
            SpUtils.obtain().save("us_ft", funAlias);
        } else if (!string.contains(funAlias)) {
            string += "_" + funAlias;
            SpUtils.obtain().save("us_ft", string);
        }
    }

    private static String getUsedFeature() {
        return SpUtils.obtain().getString("us_ft", "");
    }

    public static int getUsedFeatureCount() {
        String string = getUsedFeature();
        String[] split = string.split("_");
        //去重
        HashSet<String> hs = new HashSet<>(Arrays.asList(split));
        //去空
        Iterator<String> iterator = hs.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (TextUtils.isEmpty(next)) {
                iterator.remove();
            }
        }
        return hs.size();
    }

    private static boolean isToday(long j) {
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);
        long timeInMillis = instance.getTimeInMillis();
        if (j <= timeInMillis || j >= timeInMillis + TimeConstant.ONE_DAY) {
            return false;
        }
        return true;
    }

}
